package cn.edu.stu.syllabus.login;

import com.orhanobut.logger.Logger;

import javax.inject.Inject;

import cn.edu.stu.syllabus.di.scope.FragmentScoped;
import cn.edu.stu.syllabus.repository.token.TokenRepository;
import cn.edu.stu.syllabus.repository.token.local.TokenEntry;
import cn.edu.stu.syllabus.utils.RxSchedulerUtils;
import rx.Subscriber;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/4/24.
 */

@FragmentScoped
public class LoginPresenter implements LoginContract.Presenter {

    private LoginContract.View mView;

    private TokenRepository mTokenRepository;

    private CompositeSubscription mCompositeSubscription;

    @Inject
    public LoginPresenter(LoginContract.View view, TokenRepository tokenRepository) {
        mView = checkNotNull(view);
        mTokenRepository = checkNotNull(tokenRepository);
        mCompositeSubscription = new CompositeSubscription();
    }

    @Inject
    public void setupListener() {
        mView.setPresenter(this);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mCompositeSubscription.unsubscribe();
    }

    @Override
    public void loadToken(String code) {
        Subscription subscription = mTokenRepository.getToken(code)
                .compose(RxSchedulerUtils.<TokenEntry>io2mainSchedulersTransformer())
                .subscribe(new Subscriber<TokenEntry>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showFail();
                    }

                    @Override
                    public void onNext(TokenEntry tokenEntry) {
                        Logger.e(tokenEntry.toString());
                        mView.showSuccess(tokenEntry);
                    }
                });
        mCompositeSubscription.add(subscription);
    }
}
